package com.rongma.waterdrop.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.rongma.waterdrop.R;
import com.rongma.waterdrop.global.TimerStatus;
import com.rongma.waterdrop.listener.OnCodeTimeChangeListener;
import com.rongma.waterdrop.manager.bmobmanager.TimeManager;
import com.rongma.waterdrop.manager.bmobmanager.TimerEventManager;
import com.rongma.waterdrop.manager.bmobmanager.UserManager;
import com.rongma.waterdrop.model.Time;
import com.rongma.waterdrop.model.TimerEvent;
import com.rongma.waterdrop.receiver.TimerChangeReceiver;
import com.rongma.waterdrop.service.TimerService;
import com.rongma.waterdrop.utils.LogUtils;
import com.rongma.waterdrop.utils.TimeUtils;

import java.util.ArrayList;

/**
 * Created by RongMa on 16/5/29.
 */
public class TimerItemAdapter extends BaseAdapter
{
    private ArrayList<TimerEvent> timerEvents;
    private Context context;
    private TimerChangeReceiver timerChangeReceiver;
    private int time = 0;
    private OnCodeTimeChangeListener listener;

    public TimerItemAdapter(ArrayList<TimerEvent> timerEvents,Context context)
    {
        this.context = context;
        this.timerEvents = timerEvents;
    }

    @Override
    public int getCount() {
        return timerEvents.size();
    }

    @Override
    public Object getItem(int position) {
        return timerEvents.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        final View[] views = {convertView};
        if(views[0] == null)
        {
            views[0] = LayoutInflater.from(context).inflate(R.layout.main_timer_item_layout,null);
            holder = new ViewHolder();
            holder.ivIcon = (ImageView) views[0].findViewById(R.id.iv_timer_item_icon);
            holder.tvTitle = (TextView) views[0].findViewById(R.id.tv_timer_item_title);
            holder.tvContent = (TextView) views[0].findViewById(R.id.tv_timer_item_content);
            holder.ivStatus = (ImageView) views[0].findViewById(R.id.iv_timer_item_status);
            views[0].setTag(holder);
        }
        else
        {
            holder = (ViewHolder) views[0].getTag();
        }
        final TimerEvent event = timerEvents.get(position);
        holder.ivIcon.setBackgroundResource(event.getIconBg().intValue());
        holder.ivIcon.setImageResource(event.getIconSrc().intValue());
        holder.tvTitle.setText(event.getTitle());
        changeUIByStatus(holder,views[0],event);
        holder.ivStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(event.getStatus() == TimerStatus.START)
                {
                    event.setStatus(TimerStatus.STOP);
                    TimerEventManager.getManager(context).updateTimer(event);
                    //注销广播
                    unregisterTimerReceiver();
                    Intent intent = new Intent(context, TimerService.class);
                    context.stopService(intent);
                    changeData(event);
                    //对UI进行修改
                    changeUIByStatus(holder, views[0],event);
                }
                else
                {
                    TimerEvent stopEvent = TimerEventManager.getManager(context).setAllEventStop(timerEvents);
                    if(stopEvent != null)
                    {
                        Intent intent = new Intent(context, TimerService.class);
                        context.stopService(intent);
                        changeData(stopEvent);
                        notifyDataSetChanged();
                    }
                    event.setStatus(TimerStatus.START);
                    TimerEventManager.getManager(context).updateTimer(event);
                    //注册广播
                    registerTimerReceiver();
                    timerChangeReceiver.setListener(new TimerChangeReceiver.OnTimerChangeListener() {
                        @Override
                        public void showTime(int time) {
                            try {
                                holder.tvContent.setText(TimeUtils.getTimeByNumber(time));
                                TimerItemAdapter.this.time = time;
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    //开启服务
                    Intent intent = new Intent(context, TimerService.class);
                    context.startService(intent);
                    //对UI进行修改
                    changeUIByStatus(holder,views[0],event);
                }
            }
        });
        return views[0];
    }

    //判断时间间隔是否超过1分钟,对数据库进行操作
    //否则弹出Toast
    private void changeData(TimerEvent event) {
        if(time <= 60)
        {
            Toast.makeText(context, "时间间隔少于1分钟,不做记录!", Toast.LENGTH_SHORT).show();
        }
        else
        {
            if(event.getTitle().equals("编程"))
            {
                //修改User数据
                //修改Time数据
                UserManager.getManager(context).updateUserCodeTime("戎码",time,context);
                Time timeModel = new Time();
                timeModel.setRecordDate(TimeUtils.getDate());
                timeModel.setCodeTime((long) time);
                TimeManager.getManager(context).insertOrUpdateTime(timeModel);
                listener.onChange();

            }
            else
            {
                //修改Time数据
                Time timeModel = new Time();
                timeModel.setRecordDate(TimeUtils.getDate());
                timeModel.setSleepTime((long) time);
                TimeManager.getManager(context).insertOrUpdateTime(timeModel);
            }
        }
    }

    public void setTimeChangeListener(OnCodeTimeChangeListener listener)
    {
        this.listener = listener;
    }

    private void unregisterTimerReceiver()
    {
        if(timerChangeReceiver != null) {
            context.unregisterReceiver(timerChangeReceiver);
            timerChangeReceiver = null;
        }
    }


    private void registerTimerReceiver()
    {
        if(timerChangeReceiver == null)
        {
            timerChangeReceiver = new TimerChangeReceiver();
        }
        IntentFilter intentFilter = new IntentFilter(TimerChangeReceiver.TIMER_RECEIVER_ACTION);
        context.registerReceiver(timerChangeReceiver,intentFilter);

    }

    //通过状态修改UI
    private void changeUIByStatus(ViewHolder holder,View convertView,TimerEvent event) {
        switch (event.getStatus())
        {
            case TimerStatus.START:
                convertView.setBackgroundResource(event.getIconColor().intValue());
                holder.ivStatus.setImageResource(R.mipmap.ic_stop_white);
                try {
                    holder.tvContent.setText(TimeUtils.getTimeByNumber(event.getTime()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                holder.tvTitle.setTextColor(Color.parseColor("#FFFFFF"));
                holder.tvContent.setTextColor(Color.parseColor("#FFFFFF"));
                break;
            case TimerStatus.STOP:
                convertView.setBackgroundResource(R.color.colorPageBg);
                holder.ivStatus.setImageResource(R.mipmap.ic_start);
                holder.tvContent.setText(event.getContent());
                holder.tvTitle.setTextColor(Color.parseColor("#000000"));
                holder.tvContent.setTextColor(Color.parseColor("#666666"));
                break;
        }
    }

    private class ViewHolder
    {
        public ImageView ivIcon;
        public TextView tvTitle;
        public TextView tvContent;
        public ImageView ivStatus;
    }
}
